<template>
  <div class="app-container">
    <el-card>
      <el-card class="box-card" shadow="never">
        <div slot="header" class="clearfix">
          <span class="role-span">招标项目详情编辑</span>
          <div class="box-card-btn" v-if="pageReady">
            <el-button type="success" @click="editProject" :loading="posting" v-if="editMode">
              修改项目
            </el-button>
            <el-button type="primary" @click="createNewProject" :loading="posting" v-else>
              创建项目
            </el-button>

            <!-- 快捷入口 -->
            <router-link
              :to="{ path: '/project/process', query: { pid: this.npi.id } }"
              v-if="this.editMode"
            >
              <el-button>
                查看项目
              </el-button>
            </router-link>
          </div>
        </div>
        <el-form :model="npi" ref="projectForm" :rules="projectRules" label-width="180px">
          <el-divider content-position="left">基本信息</el-divider>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item prop="name" label="项目名称:">
                <el-input v-model="npi.name"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="code" label="项目编号:">
                {{ npi.code }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="stock" label="采购品类:">
                <stock-tree v-model="npi.stock"></stock-tree>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="description" label="项目说明:">
                <el-input
                  v-model="npi.description"
                  maxlength="200"
                  show-word-limit
                  type="textarea"
                  resize="none"
                  rows="4"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="entryTime" label="报名截止时间:">
                <el-date-picker
                  v-model="npi.entryTime"
                  type="datetime"
                  value-format="timestamp"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="openTime" label="开标时间:">
                <el-date-picker
                  v-model="npi.openTime"
                  type="datetime"
                  value-format="timestamp"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="address" label="交货地点:">
                <el-input v-model="npi.address"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item prop="descriptionOuter" label="对外文件说明:">
                <el-input
                  v-model="npi.descriptionOuter"
                  type="textarea"
                  resize="none"
                  show-word-limit
                  maxlength="300"
                  :rows="5"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="docInner" label="内部文件:">
                <el-upload
                  class="upload-demo"
                  :multiple="true"
                  :accept="fileAccept"
                  :on-success="uploadedInner"
                  :on-error="uploadError"
                  :headers="{ Authorization: token }"
                  :action="`${baseURL}/api/project/file`"
                  :limit="5"
                  :show-file-list="false"
                >
                  <el-button size="small" type="primary">点击上传</el-button>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="docOutter" label="对外文件:">
                <el-upload
                  class="upload-demo"
                  :multiple="true"
                  :accept="fileAccept"
                  :on-success="uploadedOutter"
                  :on-error="uploadError"
                  :headers="{ Authorization: token }"
                  :action="`${baseURL}/api/project/file`"
                  :limit="5"
                  :show-file-list="false"
                >
                  <el-button size="small" type="primary">点击上传</el-button>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item prop="allApply" label="是否全部报价:">
                <el-radio v-model="npi.allApply" :label="true">全部报价</el-radio>
                <el-radio v-model="npi.allApply" :label="false">部分报价</el-radio>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="paymentClause" label="付款条件:">
                <el-input v-model="npi.paymentClause"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="contact" label="合同对接人及联系方式:">
                <el-input v-model="npi.contact"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
      <el-card class="box-card" shadow="never">
        <div slot="header" class="clearfix">
          <span class="role-span">
            询价清单
            <el-switch
              v-model="planBatchStatus"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-text="批量修改(*号字段)"
              size="small"
              v-if="!editMode"
            ></el-switch>
          </span>
          <div class="box-card-btn" v-if="pageReady">
            <el-button type="primary" @click="showPlanListDialog = true" v-if="!editMode">
              选择计划
            </el-button>
            <el-button type="danger" @click="removePlan" v-if="!editMode">
              移除计划
            </el-button>
          </div>
          <plan-apply-list
            ref="planApplyList"
            v-model="npi.projectPlans"
            :checkMode="editMode"
            :planBatchStatus="planBatchStatus"
          ></plan-apply-list>
        </div>
      </el-card>
    </el-card>

    <supplier-select-table v-if="editMode" :profile="this.npi"></supplier-select-table>

    <el-dialog :visible.sync="showPlanListDialog" append-to-body width="90%" top="20px">
      <plan-list mode="selection" v-if="showPlanListDialog" @add-plan="addPlan"></plan-list>
    </el-dialog>
  </div>
</template>

<script>
  import { resultFormatter } from '@/utils';
  import * as ProjectRequest from '@/api/project';
  import * as PlanRequest from '@/api/plan';

  import FormRuleConf from '@/FormRuleConf';
  import { fileAccept } from '@/settings';
  import { getToken } from '@/utils/auth';
  import StockTree from '@/components/StockTree';
  import PlanList from '@/views/plan/list';
  import SupplierSelectTable from './supplierSelectTable';
  import PlanApplyList from './planApplyList';

  const DATA_TMP = {
    name: '',
    code: '',
    stock: [],
    description: '',
    entryTime: '',
    openTime: '',
    address: '',
    descriptionOuter: '',
    docInner: [], // 内部文件
    docOutter: [], // 外部文件
    allApply: true,
    paymentClause: '',
    contact: '',
    planList: [],
  };

  export default {
    name: 'ProjectProfile',
    data() {
      return {
        ...FormRuleConf.Project,
        npi: {
          ...DATA_TMP,
        },
        fileAccept,
        pageReady: true,
        posting: false,
        baseURL: process.env.VUE_APP_BASE_API,
        token: getToken(),

        planBatchStatus: false,
        showPlanListDialog: false,
      };
    },
    components: {
      StockTree,
      PlanList,
      PlanApplyList,
      SupplierSelectTable,
    },
    watch: {
      $route() {
        this.init();
      },
      'npi.allApply'() {
        this.npi.allApply = !!this.npi.allApply;
      },
    },
    computed: {
      editMode() {
        return !!this.npi.id;
      },
    },
    mounted() {
      this.init();
    },
    methods: {
      /**
       * 初始化
       */
      init() {
        this.checkPid();
        if (this.editMode) {
          this.getProjectProfile();
        } else {
          this.getPlansByQuery();
        }
      },
      /**
       * 检查pid参数
       */
      checkPid() {
        const { pid } = this.$route.query;
        if (pid) {
          this.$set(this.npi, 'id', pid);
        }
      },
      /**
       * 通过URL参数获取plan
       */
      getPlansByQuery() {
        const { plan_ids } = this.$route.query;
        if (plan_ids) {
          PlanRequest.getByIds({
            planIds: plan_ids,
          }).then((res) => {
            this.$set(
              this.npi,
              'projectPlans',
              res.map((plan) => {
                return {
                  ...plan,
                  detail: JSON.parse(plan.detail),
                };
              }),
            );
          });
        }
      },
      /**
       * 获取项目信息
       */
      getProjectProfile() {
        ProjectRequest.getProfile({
          id: this.npi.id,
        }).then((res) => {
          this.npi = {
            ...res,
            projectPlans: res.projectPlans.map((plan) => {
              return {
                ...plan,
                detail: JSON.parse(plan.detail),
              };
            }),
          };
        });
      },
      /**
       * 提交项目
       */
      createNewProject() {
        if (this.posting) return;
        this.$refs.projectForm.validate((valid) => {
          if (!valid) return;

          this.$confirm('创建项目之后,项目中的计划清单不能修改,请确认', '提示').then((res) => {
            this.posting = true;
            const { projectPlans } = this.npi;
            const plans = projectPlans.map((plan) => {
              return {
                ...plan,
                detail: JSON.stringify(plan.detail),
              };
            });

            ProjectRequest.add({
              ...this.npi,
              projectPlans: plans,
            })
              .then((res) => {
                this.$message.success('创建招标项目成功');
                this.$router.replace({
                  name: 'ProjectProfile',
                  query: {
                    pid: res.id,
                  },
                });
              })
              .finally(() => {
                this.posting = false;
              });
          });
        });
      },
      /**
       * 修改项目
       */
      editProject() {
        if (this.posting) return;
        this.posting = true;

        const { projectPlans } = this.npi;
        const plans = projectPlans.map((plan) => {
          return {
            ...plan,
            detail: JSON.stringify(plan.detail),
          };
        });

        ProjectRequest.edit({
          ...this.npi,
          projectPlans: plans,
        })
          .then((res) => {
            this.$message.success('修改招标项目成功');
          })
          .finally(() => {
            this.posting = false;
          });
      },
      /**
       * 上传处理
       */
      uploadedInner(res, file, fileList) {
        this.$set(
          this.npi,
          'docInner',
          fileList.map((file) => file.response.file),
        );
        this.$message.success('内部文件上传成功');
      },
      uploadedOutter(res, file, fileList) {
        this.$set(
          this.npi,
          'docOutter',
          fileList.map((file) => file.response.file),
        );
        this.$message.success('外部文件上传成功');
      },
      uploadError() {
        this.$message.error('文件上传失败');
      },
      /**
       * 增加计划
       */
      addPlan(plans) {
        this.showPlanListDialog = false;
        this.$set(this.npi, 'projectPlans', this.npi.projectPlans.concat(plans));
      },
      /**
       * 移除计划
       */
      removePlan() {
        this.$set(
          this.npi,
          'projectPlans',
          this.npi.projectPlans.filter(
            (plan) => !this.$refs['planApplyList'].selectedData.includes(plan.id),
          ),
        );
      },
    },
  };
</script>

<style lang="scss" scoped></style>
